<template>
  <!-- 微信登录 -->
  <layout title="注册" background="#fff">
    <view class="flex-center" style="height: 100%">
      <!-- <button class="default-button" open-type="getUserInfo" @getuserinfo="getuserinfo"> -->
      <view class="" style="width: 100%">
        <!-- <button class="default-button" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
						<text>微信用户一键登录</text>
					</button> -->
        <button class="default-button" @tap="triggerToLoginByWxLogin">
          <text>微信授权登录</text>
        </button>
        <!-- <button class="default-button" @tap="wxChatLogin('WX')">
          <text>使用授权码登录</text>
        </button>
        <button class="default-button" @tap="showModal">
          <text>显示本地数据</text>
        </button> -->
        <!-- 
					<button class="default-button" @tap="showData">
						<text>显示微信授权数据</text>
					</button> -->
      </view>
    </view>
  </layout>
</template>
<script>
export default {
  data() {
    return {
      navigationBarStyle: {
        background: "",
        color: "black",
        iconText: "注册", //导航栏文字
      },
      phoneNo: "",
      userInfoModel: {
        userName: "",
        userHead: "",
        sex: "",
        city: "",
        province: "",
        country: "",
        userTel: "",
      },
      wxGetMes: {
        //从微信获取的信息
        code: "",
        iv: "",
        encryptedData: "",
        openId: "",
      },
      data: null,
    };
  },
  mounted() {
    const _this = this;
    this.$bridge.registerHandler(
      "triggerToLoginByWxAccess",
      (data, responseCallback) => {
        responseCallback(data);
        _this.data = data;
        (async function () {
          try {
            data = JSON.parse(data);
          } catch (err) {
            // _data = data;
          }
          _this.wxGetMes.code = data.code;
          _this.wxChatLogin("WX");
        })();
      }
    );
  },
  onLoad() {
    // const _this = this;
    // uni.login({
    //   success(res) {
    //     _this.wxGetMes.code = res.code;
    //   },
    // });
    // this.$u.vuex("vuex_identity", 2);
  },
  methods: {
    triggerToLoginByWxLogin() {
      this.$bridge.callHandler(
        "triggerToLoginWithWxAccess",
        JSON.stringify({}),
        (args) => {}
      );
    },
    getPhoneNumber(e) {
      // 授权后 微信获取用户手机号一键登录
      const _this = this;
      if (e.detail.iv && e.detail.encryptedData) {
        _this.wxGetMes.iv = e.detail.iv;
        _this.wxGetMes.encryptedData = e.detail.encryptedData;
        uni.checkSession({
          success(d) {
            //session_key 未过期，并且在本生命周期一直有效
            _this.wxChatLogin();
          },
          fail() {
            // session_key 已经失效，需要重新执行登录流程
            uni.login({
              success(res) {
                _this.wxGetMes.code = res.code;
              },
            });
          },
        });
      } else {
        uni.showToast({
          title: "登录信息已过期请重新获取选择登录号",
          icon: "none",
          duration: 1000,
        });
      }
    },
    async queryHasRunningPermission() {
      const data = await this.$u.api.queryRealNameProcess();
      return data.data && data.data.type === 5;
    },
    async hasRunner() {
      let isRunner = String(this.vuex_identity) === "1";
      if (await this.queryHasRunningPermission()) {
        this.$u.vuex("vuex_flag", "runner");
      } else {
        this.$u.toast("该账户没有认证跑腿员");
        isRunner = false;
      }
      await new Promise((r) => setTimeout(r, 1000));

      uni.reLaunch({
        url: isRunner ? "/pages/sys/home/hall" : "/pages/sys/home/index",
      });
      return isRunner;
    },
    getInfo() {
      const _this = this;
      _this.$u.api.getUserMes().then((res) => {
        if (res.code == 200) {
          _this.$u.vuex("vuex_user", res.data);
        }
      });
    },
    async wxChatLogin(type = "WX_APPLET") {
      // code登录
      const _this = this;
      uni.showToast({
        icon: "loading",
        duration: 2000,
      });
      // var pa = {
      // 	code: _this.wxGetMes.code,
      // 	encryptedData: _this.wxGetMes.encryptedData,
      // 	iv: _this.wxGetMes.iv,
      // 	type: 'WX_APPLET'
      // }
      const cb = () => {
        if (String(_this.vuex_identity) === "2") {
          uni.reLaunch({
            url: "/pages/sys/home/index",
          });
          return;
        }
        _this.hasRunner();
      };
      var pa = {
        jsCode: this.wxGetMes.code,
        // data: _this.wxGetMes.encryptedData,
        // iv: _this.wxGetMes.iv,
        type,
      };
      try {
        const res = await this.$u.api.wxLogin(pa);
        if (Number(res.data.telFlg) === 1) {
          // 绑定手机号
          uni.navigateTo({
            url: `/pages/sys/login/inputPhone?type=bind&openId=${res.data.openId}`,
          });
          return;
        } else if (res.data.token) {
          uni.setStorageSync("wxxcxToken", res.data.token);
          uni.showToast({
            title: "登录成功",
            icon: "none",
            duration: 1000,
          });
          cb();
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: "登录失败，请重新登录",
          icon: "none",
          duration: 1000,
        });
      }
    },
  },
};
</script>
<style lang="scss">
</style>
